/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package View;

import Entity.Owner;
import Services.OwnerService;
import Services.exceptions.NonexistentEntityException;
import java.util.Calendar;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.SpinnerDateModel;

/**
 *
 * @author arch
 */
public class DOwner extends javax.swing.JDialog {

  /**
   * Creates new form DOwner
   */
    private EntityManagerFactory emf=null;
    
  public DOwner(java.awt.Frame parent, boolean modal) {
    super(parent, modal);
    initComponents();
    
    Calendar cal = Calendar.getInstance();
    
    cal.set(Calendar.YEAR, 1900);
    cal.set(Calendar.MONTH, 1);
    cal.set(Calendar.DAY_OF_MONTH, 1);
    
    Date start = cal.getTime();
    
    cal.set(Calendar.YEAR, 2050);
    cal.set(Calendar.MONTH, 1);
    cal.set(Calendar.DAY_OF_MONTH, 1);
    
    Date end = cal.getTime();
    
    spinnerModel = new SpinnerDateModel(start, start, end, Calendar.YEAR);
    spinnerDate.setModel(spinnerModel);
    emf=Persistence.createEntityManagerFactory("HPVASPU");
    
    super.setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE);
    super.pack();
    super.setVisible(false);
    super.setLocationRelativeTo(this);
  }

  /**
   * This method is called from within the constructor to initialize the form.
   * WARNING: Do NOT modify this code. The content of this method is always
   * regenerated by the Form Editor.
   */
  @SuppressWarnings("unchecked")
  // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
  private void initComponents() {

    tfSSN = new javax.swing.JTextField();
    lLastname = new javax.swing.JLabel();
    tfName = new javax.swing.JTextField();
    jLabel2 = new javax.swing.JLabel();
    bClose = new javax.swing.JButton();
    jLabel1 = new javax.swing.JLabel();
    lName = new javax.swing.JLabel();
    tfLastname = new javax.swing.JTextField();
    spinnerDate = new javax.swing.JSpinner();
    bSave = new javax.swing.JButton();
    bDelete = new javax.swing.JButton();

    setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

    lLastname.setText("Lastname:");

    jLabel2.setText("Birth-date:");

    bClose.setText("Close");
    bClose.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        bCloseActionPerformed(evt);
      }
    });

    jLabel1.setText("SSN:");

    lName.setText("Name:");

    bSave.setText("Save");
    bSave.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        bSaveActionPerformed(evt);
      }
    });

    bDelete.setText("Delete");
    bDelete.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        bDeleteActionPerformed(evt);
      }
    });

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(layout.createSequentialGroup()
        .addContainerGap()
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
          .addComponent(lName)
          .addComponent(jLabel1))
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
          .addComponent(tfName)
          .addComponent(tfSSN, javax.swing.GroupLayout.DEFAULT_SIZE, 190, Short.MAX_VALUE))
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
          .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
            .addComponent(bDelete)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(bSave)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(bClose))
          .addGroup(layout.createSequentialGroup()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
              .addComponent(lLastname)
              .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
              .addComponent(tfLastname)
              .addGroup(layout.createSequentialGroup()
                .addGap(0, 0, Short.MAX_VALUE)
                .addComponent(spinnerDate, javax.swing.GroupLayout.PREFERRED_SIZE, 223, javax.swing.GroupLayout.PREFERRED_SIZE)))))
        .addContainerGap())
    );
    layout.setVerticalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
        .addContainerGap()
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
          .addComponent(lName)
          .addComponent(lLastname)
          .addComponent(tfName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
          .addComponent(tfLastname, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
          .addComponent(jLabel1)
          .addComponent(tfSSN, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
          .addComponent(jLabel2)
          .addComponent(spinnerDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
          .addComponent(bClose)
          .addComponent(bSave)
          .addComponent(bDelete))
        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    );

    pack();
  }// </editor-fold>//GEN-END:initComponents

  private void bCloseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bCloseActionPerformed
    
    setVisible(false);
  }//GEN-LAST:event_bCloseActionPerformed

  private void bDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bDeleteActionPerformed
    
    if (!saved) {
      JOptionPane.showMessageDialog(this, "Pet not saved yet", "Info", JOptionPane.INFORMATION_MESSAGE);
      return;
    }
    int op = DeleteCancel("Are You Sure?", "Delete");
    if (op == JOptionPane.NO_OPTION) return;
    
      // Llamar al DAO aqui'
    OwnerService os=new OwnerService(emf);
        try {
            os.destroy(owner.getId());
        } catch (NonexistentEntityException ex) {
            Logger.getLogger(DOwner.class.getName()).log(Level.SEVERE, null, ex);
            JOptionPane.showMessageDialog(this,"Owner with this id wasn't found in database");
        }
    setVisible(false);
  }//GEN-LAST:event_bDeleteActionPerformed

  private void bSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bSaveActionPerformed
    
    boolean ok = true;
    
    // Chekear valores en los campos aqui'
    // asigne el resultado a ok
    
    if (!ok) {
      JOptionPane.showMessageDialog(this, "Invalid data", "Error", JOptionPane.ERROR_MESSAGE);
      return;
    }
    saved = true;
      owner.setName(tfName.getText());
      owner.setLastname(tfLastname.getText());
      owner.setSSN(tfSSN.getText());
      owner.setBirthdate(spinnerModel.getDate());
    // llamar al DAO aqui'
    OwnerService os=new OwnerService(emf);
    os.create(owner);
    clear();
  }//GEN-LAST:event_bSaveActionPerformed

  public void set(Owner o) {
    
    if (o == null) {
      saved = false;
      clear();
      owner = new Owner();
      setTitle("New Owner");
    } else {
      owner = o;
      
      saved = true;
      setTitle(o.getName());
      tfName.setText(o.getName());
      tfLastname.setText(o.getLastname());
      tfSSN.setText(o.getSSN());
      spinnerModel.setValue(o.getBirthdate());
    }
  }
  
  public Owner get() {
    return owner;
  }
  
  public void clear() {
    
    tfName.setText("");
    tfLastname.setText("");
    tfSSN.setText("");
    spinnerModel.setValue(spinnerModel.getStart());
  }
  
  public int DeleteCancel(String message, String title) {
    
    Object[] options = {"Yes", "Cancel"};
    int op = JOptionPane.showOptionDialog(this, message, title,
                                          JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE,
                                          null, options, JOptionPane.YES_OPTION);
    return op;
  }
  
  boolean saved;
  SpinnerDateModel spinnerModel;
  Owner owner;
  
  // Variables declaration - do not modify//GEN-BEGIN:variables
  private javax.swing.JButton bClose;
  private javax.swing.JButton bDelete;
  private javax.swing.JButton bSave;
  private javax.swing.JLabel jLabel1;
  private javax.swing.JLabel jLabel2;
  private javax.swing.JLabel lLastname;
  private javax.swing.JLabel lName;
  private javax.swing.JSpinner spinnerDate;
  private javax.swing.JTextField tfLastname;
  private javax.swing.JTextField tfName;
  private javax.swing.JTextField tfSSN;
  // End of variables declaration//GEN-END:variables
}
